// 工单管理JavaScript
class WorkOrderManagement {
    constructor() {
        this.currentPage = 1;
        this.pageSize = 20;
        this.totalPages = 1;
        
        // 从配置中获取API地址
        this.readApiUrl = window.ApiConfig?.readApiUrl || 'http://localhost:5089/api';
        this.writeApiUrl = window.ApiConfig?.writeApiUrl || 'http://localhost:5090/api';
        
        this.init();
    }

    // 初始化
    init() {
        this.bindEvents();
        this.clearSelection(); // 初始化时清除选择状态
        this.loadWorkOrders();
    }

    // 绑定事件
    bindEvents() {
        // 简单搜索按钮
        $('#btnSearch').on('click', () => {
            this.currentPage = 1;
            this.loadWorkOrders();
        });

        // 简单重置按钮
        $('#btnReset').on('click', () => {
            this.resetSimpleSearch();
            this.currentPage = 1;
            this.loadWorkOrders();
        });

        // 高级查询按钮
        $('#btnAdvancedSearch').on('click', () => {
            this.toggleAdvancedSearch();
        });

        // 高级搜索执行按钮
        $('#btnAdvancedSearchExecute').on('click', () => {
            this.currentPage = 1;
            this.loadWorkOrders();
        });

        // 高级搜索重置按钮
        $('#btnAdvancedReset').on('click', () => {
            this.resetAdvancedSearch();
        });

        // 收起高级搜索按钮
        $('#btnCollapseSearch').on('click', () => {
            this.hideAdvancedSearch();
        });

        // 新增工单按钮
        $('#btnAdd').on('click', () => {
            this.showCreateWorkOrderModal();
        });

        // 顶部操作按钮
        $('#btnStart').on('click', () => {
            this.startSelectedWorkOrder();
        });

        $('#btnFinish').on('click', () => {
            this.finishSelectedWorkOrder();
        });

        $('#btnDelete').on('click', () => {
            this.deleteSelectedWorkOrder();
        });

        // 导出按钮
        $('#btnExport').on('click', () => {
            this.exportWorkOrders();
        });

        // 回车搜索
        $('.form-control').on('keypress', (e) => {
            if (e.which === 13) {
                this.currentPage = 1;
                this.loadWorkOrders();
            }
        });
    }

    // 获取搜索条件
    getSearchParams() {
        const params = {
            index: this.currentPage,
            size: this.pageSize
        };

        // 基本搜索条件
        const workOrderCode = $('#searchCode').val().trim();
        if (workOrderCode) params.workOrderCode = workOrderCode;

        // 高级搜索条件（只在高级搜索展开时才获取）
        if ($('#advancedSearchArea').is(':visible')) {
            const productCode = $('#searchProductCode').val().trim();
            const productName = $('#searchProductName').val().trim();
            const spec = $('#searchSpec').val().trim();
            const unit = $('#searchUnit').val().trim();
            const actualQuantity = $('#searchActualQuantity').val();
            const status = $('#searchStatus').val();
            const createBy = $('#searchCreateBy').val().trim();
            
            // 时间查询条件
            const plannedStartTimeStart = $('#searchPlannedStartTimeStart').val();
            const plannedStartTimeEnd = $('#searchPlannedStartTimeEnd').val();
            const plannedEndTimeStart = $('#searchPlannedEndTimeStart').val();
            const plannedEndTimeEnd = $('#searchPlannedEndTimeEnd').val();
            const actualStartTimeStart = $('#searchActualStartTimeStart').val();
            const actualStartTimeEnd = $('#searchActualStartTimeEnd').val();
            const actualEndTimeStart = $('#searchActualEndTimeStart').val();
            const actualEndTimeEnd = $('#searchActualEndTimeEnd').val();
            const createTimeStart = $('#searchCreateTimeStart').val();
            const createTimeEnd = $('#searchCreateTimeEnd').val();

            // 只添加有值的参数
            if (productCode) params.productCode = productCode;
            if (productName) params.productName = productName;
            if (spec) params.spec = spec;
            if (unit) params.unit = unit;
            if (actualQuantity) params.actualQuantity = parseInt(actualQuantity);
            if (status) params.status = status;
            if (createBy) params.createBy = createBy;
            
            if (plannedStartTimeStart) params.plannedStartTimeStart = plannedStartTimeStart;
            if (plannedStartTimeEnd) params.plannedStartTimeEnd = plannedStartTimeEnd;
            if (plannedEndTimeStart) params.plannedEndTimeStart = plannedEndTimeStart;
            if (plannedEndTimeEnd) params.plannedEndTimeEnd = plannedEndTimeEnd;
            if (actualStartTimeStart) params.actualStartTimeStart = actualStartTimeStart;
            if (actualStartTimeEnd) params.actualStartTimeEnd = actualStartTimeEnd;
            if (actualEndTimeStart) params.actualEndTimeStart = actualEndTimeStart;
            if (actualEndTimeEnd) params.actualEndTimeEnd = actualEndTimeEnd;
            if (createTimeStart) params.createTimeStart = createTimeStart;
            if (createTimeEnd) params.createTimeEnd = createTimeEnd;
        }

        return params;
    }

    // 加载工单数据
    async loadWorkOrders() {
        try {
            this.showLoading();
            const params = this.getSearchParams();
            const queryString = new URLSearchParams(params).toString();
            
            const response = await fetch(`${this.readApiUrl}/WorkOrder/page?${queryString}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (result.code === 200) {
                this.renderTable(result.pageData);
                this.renderPagination(result.totaPage, result.totaCount);
            } else {
                this.showError('获取工单数据失败：' + result.msg);
            }
        } catch (error) {
            console.error('加载工单数据失败:', error);
            this.showError('加载数据失败，请稍后重试');
        } finally {
            this.hideLoading();
        }
    }

    // 渲染表格
    renderTable(data) {
        const tbody = $('#workOrderTableBody');
        tbody.empty();

        if (!data || data.length === 0) {
            tbody.append(`
                <tr>
                    <td colspan="17" class="text-center text-muted py-4">暂无数据</td>
                </tr>
            `);
            return;
        }

        data.forEach((item, index) => {
            // 调试：输出当前工单信息
            console.log(`渲染工单 ${item.id}: ${item.code}, 状态: ${item.status}`);
            
            const row = `
                <tr>
                    <td>
                        <input type="radio" name="selectedWorkOrder" value="${item.id}" class="workorder-select" data-status="${item.status || '未开始'}" onchange="workOrderMgr.onWorkOrderSelect(${item.id}, this.getAttribute('data-status'))" />
                    </td>
                    <td>${(this.currentPage - 1) * this.pageSize + index + 1}</td>
                    <td>
                        <a href="javascript:void(0)" class="work-order-code" 
                           onclick="workOrderMgr.showWorkOrderDetail(${item.id})">
                            ${item.code}
                        </a>
                    </td>
                    <td>
                        <div class="d-flex align-items-center">
                            <span class="badge bg-primary me-2">${item.productCode || ''}</span>
                        </div>
                    </td>
                    <td>${item.productCode || ''}</td>
                    <td>${item.productName || ''}</td>
                    <td>${item.spec || ''}</td>
                    <td>${item.unit || ''}</td>
                    <td>${item.plannedQuantity || 0}</td>
                    <td>
                        <span class="status-badge status-${item.status}">
                            ${item.status || '未知'}
                        </span>
                    </td>
                    <td>${this.formatDateTime(item.plannedStartTime)}</td>
                    <td>${this.formatDateTime(item.plannedEndTime)}</td>
                    <td>${this.formatDateTime(item.actualStartTime)}</td>
                    <td>${this.formatDateTime(item.actualEndTime)}</td>
                    <td>
                        <span class="process-count-badge">
                            ${item.processCount || 0}
                        </span>
                    </td>
                    <td>${item.createBy || ''}</td>
                    <td>
                        <div class="btn-group btn-group-sm">
                            <button type="button" class="btn btn-outline-primary" 
                                    onclick="workOrderMgr.showWorkOrderDetail(${item.id})">
                                详情
                            </button>
                            <button type="button" class="btn btn-outline-secondary" 
                                    onclick="workOrderMgr.editWorkOrder(${item.id})">
                                编辑
                            </button>
                        </div>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    // 渲染操作按钮（已移除，现在使用顶部按钮）
    renderActionButtons(item) {
        // 该方法已不再使用，所有操作通过顶部按钮完成
        return '';
    }

    // 渲染分页
    renderPagination(totalPages, totalCount) {
        this.totalPages = totalPages;
        const pagination = $('#pagination');
        pagination.empty();

        if (totalPages <= 1) return;

        // 上一页
        if (this.currentPage > 1) {
            pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="workOrderMgr.goToPage(${this.currentPage - 1})">上一页</a>
                </li>
            `);
        }

        // 页码
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(totalPages, this.currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const activeClass = i === this.currentPage ? 'active' : '';
            pagination.append(`
                <li class="page-item ${activeClass}">
                    <a class="page-link" href="javascript:void(0)" onclick="workOrderMgr.goToPage(${i})">${i}</a>
                </li>
            `);
        }

        // 下一页
        if (this.currentPage < totalPages) {
            pagination.append(`
                <li class="page-item">
                    <a class="page-link" href="javascript:void(0)" onclick="workOrderMgr.goToPage(${this.currentPage + 1})">下一页</a>
                </li>
            `);
        }

        // 显示总数
        pagination.append(`
            <li class="page-item disabled">
                <span class="page-link">共 ${totalCount} 条</span>
            </li>
        `);
    }

    // 跳转页面
    goToPage(page) {
        if (page < 1 || page > this.totalPages || page === this.currentPage) return;
        this.currentPage = page;
        this.loadWorkOrders();
    }

    // 显示工单详情
    async showWorkOrderDetail(workOrderId) {
        try {
            this.showLoading();
            
            // 调试：输出正在调用的工单ID
            console.log('正在获取工单详情，工单ID：', workOrderId);
            
            const response = await fetch(`${this.readApiUrl}/WorkOrder/${workOrderId}`);
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (result.code === 200) {
                // 调试：输出后端返回的数据结构
                console.log('工单详情数据：', result.data);
                console.log('工序数据：', result.data.processes);
                
                const detailHtml = this.renderWorkOrderDetail(result.data);
                this.showLayerModal(detailHtml);
            } else {
                this.showError('获取工单详情失败：' + result.msg);
            }
        } catch (error) {
            console.error('获取工单详情失败:', error);
            this.showError('获取详情失败，请稍后重试');
        } finally {
            this.hideLoading();
        }
    }

    // 渲染工单详情
    renderWorkOrderDetail(data) {
        // 调试：确认工序数据
        console.log('渲染工单详情，工序数据：', data.processes);
        console.log('工序数据类型：', typeof data.processes);
        console.log('工序数组长度：', data.processes ? data.processes.length : 'null/undefined');
        
        // 生成工序表格HTML
        const processTableHtml = this.renderProcessTable(data.processes || []);
        console.log('工序表格HTML：', processTableHtml);
        
        const content = `
            <div class="row">
                <!-- 工单基本信息 -->
                <div class="col-12">
                    <h6 class="border-bottom pb-2 mb-3">工单信息</h6>
                    <div class="row">
                        <div class="col-md-4 mb-2">
                            <strong>工单编号：</strong>${data.code}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>产品编号：</strong>${data.productCode || ''}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>产品名称：</strong>${data.productName || ''}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>规格：</strong>${data.spec || ''}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>单位：</strong>${data.unit || ''}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>计划数量：</strong>${data.plannedQuantity || 0}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>实际数量：</strong>${data.actualQuantity || 0}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>良品数：</strong>${data.goodQuantity || 0}
                        </div>
                        <div class="col-md-4 mb-2">
                            <strong>不良品数：</strong>${data.badQuantity || 0}
                        </div>
                        <div class="col-md-6 mb-2">
                            <strong>计划开始时间：</strong>${this.formatDateTime(data.plannedStartTime)}
                        </div>
                        <div class="col-md-6 mb-2">
                            <strong>计划结束时间：</strong>${this.formatDateTime(data.plannedEndTime)}
                        </div>
                        <div class="col-12 mb-2">
                            <strong>备注：</strong>${data.remark || '无'}
                        </div>
                    </div>
                </div>
                
                <!-- 工序信息 -->
                <div class="col-12 mt-4">
                    <h6 class="border-bottom pb-2 mb-3">工序信息</h6>
                    ${processTableHtml}
                </div>
            </div>
        `;
        
        return content;
    }

    // 渲染工序表格
    renderProcessTable(processes) {
        try {
            // 调试：输出工序数据
            console.log('渲染工序表格，接收到的工序数据：', processes);
            console.log('工序数据类型：', typeof processes);
            console.log('是否为数组：', Array.isArray(processes));
            
            if (!processes || processes.length === 0) {
                console.log('工序数据为空，返回默认提示');
                return '<p class="text-muted">暂无工序信息</p>';
            }

            // 检查第一个工序的数据结构
            if (processes.length > 0) {
                console.log('第一个工序数据：', processes[0]);
                console.log('工序属性：', Object.keys(processes[0]));
            }

            let html = `
                <div class="table-responsive">
                    <table class="table table-sm table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>序号</th>
                                <th>工序编号</th>
                                <th>工序名称</th>
                                <th>计划数量</th>
                                <th>已报工数</th>
                                <th>良品数</th>
                                <th>不良品数</th>
                                <th>状态</th>
                                <th>分派情况</th>
                            </tr>
                        </thead>
                        <tbody>
            `;

            processes.forEach((process, index) => {
                try {
                    console.log(`渲染第${index + 1}个工序：`, process);
                    const assignInfo = this.renderAssignInfo(process.assigns || []);
                    html += `
                        <tr>
                            <td>${process.sequence || (index + 1)}</td>
                            <td>${process.processCode || ''}</td>
                            <td>${process.processName || ''}</td>
                            <td>${process.plannedQuantity || 0}</td>
                            <td>${process.reportedQuantity || 0}</td>
                            <td>${process.goodQuantity || 0}</td>
                            <td>${process.badQuantity || 0}</td>
                            <td>
                                <span class="status-badge status-${process.status || '未知'}">
                                    ${process.status || '未知'}
                                </span>
                            </td>
                            <td>${assignInfo}</td>
                        </tr>
                    `;
                } catch (processError) {
                    console.error(`渲染第${index + 1}个工序时出错：`, processError);
                    html += `
                        <tr>
                            <td colspan="9" class="text-danger">工序 ${index + 1} 渲染出错</td>
                        </tr>
                    `;
                }
            });

            html += `
                        </tbody>
                    </table>
                </div>
            `;

            console.log('生成的工序表格HTML长度：', html.length);
            console.log('生成的工序表格HTML（前500字符）：', html.substring(0, 500));
            return html;
        } catch (error) {
            console.error('渲染工序表格时出错：', error);
            return '<p class="text-danger">工序信息加载失败</p>';
        }
    }

    // 渲染分派信息
    renderAssignInfo(assigns) {
        try {
            console.log('渲染分派信息，接收到的数据：', assigns);
            console.log('分派数据类型：', typeof assigns);
            console.log('是否为数组：', Array.isArray(assigns));
            
            if (!assigns || !Array.isArray(assigns) || assigns.length === 0) {
                console.log('分派数据为空，返回默认提示');
                return '<span class="text-muted">未分派</span>';
            }

            const result = assigns.map(assign => {
                try {
                    console.log('渲染单个分派：', assign);
                    const employeeName = assign.employeeName || '未知员工';
                    const quantity = assign.quantity || 0;
                    return `<span class="badge bg-info me-1">${employeeName}(${quantity})</span>`;
                } catch (assignError) {
                    console.error('渲染单个分派时出错：', assignError);
                    return '<span class="badge bg-warning me-1">分派信息错误</span>';
                }
            }).join('');
            
            console.log('生成的分派信息HTML：', result);
            return result || '<span class="text-muted">未分派</span>';
        } catch (error) {
            console.error('渲染分派信息时出错：', error);
            return '<span class="text-danger">分派信息加载失败</span>';
        }
    }

    // 编辑工单
    async editWorkOrder(workOrderId) {
        try {
            this.showLoading();
            
            // 获取工单详情
            const response = await fetch(`${this.readApiUrl}/WorkOrder/${workOrderId}`);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            if (result.code !== 200) {
                throw new Error(result.msg || '获取工单详情失败');
            }
            
            // 设置编辑模式数据
            this.editingWorkOrderId = workOrderId;
            this.selectedProcesses = result.data.processes || [];
            
            // 确保工序数据包含必要字段
            this.selectedProcesses.forEach((process, index) => {
                process.sequence = index + 1;
                if (!process.reportingPermissions) {
                    process.reportingPermissions = '无';
                }
                if (!process.ratio) {
                    process.ratio = 1;
                }
                if (!process.status) {
                    process.status = '未开始';
                }
            });
            
            const content = this.renderCreateWorkOrderForm();
            
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    this.createModalIndex = layer.open({
                        type: 1,
                        title: '编辑工单',
                        area: ['95%', '85%'],
                        maxmin: true,
                        content: content,
                        btn: ['更新', '取消'],
                        btnAlign: 'c',
                        success: async () => {
                            // 先加载产品选项
                            await this.loadProductsToSelect();
                            // 填充表单数据
                            this.fillWorkOrderForm(result.data);
                            // 渲染工序表格
                            this.renderSelectedProcessTable();
                            
                            // 设置产品选择监听器，确保切换产品时自动更新相关字段
                            if (typeof layui !== 'undefined') {
                                layui.use('form', (form) => {
                                    this.setupProductSelectListener(form);
                                });
                            }
                        },
                        yes: (index) => {
                            this.updateWorkOrder(index);
                        },
                        cancel: () => {
                            this.clearEditingData();
                        }
                    });
                });
            }
        } catch (error) {
            console.error('编辑工单失败:', error);
            this.showError('编辑工单失败：' + error.message);
        } finally {
            this.hideLoading();
        }
    }

    // 填充工单表单数据
    fillWorkOrderForm(workOrderData) {
        const form = document.getElementById('workOrderForm');
        if (!form) return;

        // 填充基本信息
        this.setFormValue('code', workOrderData.code);
        this.setFormValue('productCode', workOrderData.productCode);
        this.setFormValue('spec', workOrderData.spec);
        this.setFormValue('plannedQuantity', workOrderData.plannedQuantity);
        this.setFormValue('remark', workOrderData.remark);
        
        // 延迟设置下拉框值，确保产品选项已经加载完成
        setTimeout(() => {
            // 设置产品名称下拉框
            this.setSelectValue('productName', workOrderData.productName);
            
            // 设置单位下拉框
            this.setSelectValue('unit', workOrderData.unit);
            
            // 再次设置产品相关字段，确保显示正确
            this.setFormValue('productCode', workOrderData.productCode);
            this.setFormValue('spec', workOrderData.spec);
        }, 200);
        
        // 处理时间字段
        if (workOrderData.plannedStartTime) {
            this.setFormValue('plannedStartTime', this.formatDateTimeForInput(workOrderData.plannedStartTime));
        }
        if (workOrderData.plannedEndTime) {
            this.setFormValue('plannedEndTime', this.formatDateTimeForInput(workOrderData.plannedEndTime));
        }
    }

    // 设置表单字段值
    setFormValue(fieldName, value) {
        const field = document.getElementById(fieldName) || document.querySelector(`[name="${fieldName}"]`);
        if (field && value !== undefined && value !== null) {
            field.value = value;
        }
    }
    
    // 设置下拉框值（特殊处理layui select）
    setSelectValue(fieldName, value) {
        const select = document.getElementById(fieldName) || document.querySelector(`[name="${fieldName}"]`);
        if (select && value !== undefined && value !== null) {
            // 检查选项是否存在，如果不存在则创建
            let optionExists = false;
            for (let i = 0; i < select.options.length; i++) {
                if (select.options[i].value === value) {
                    optionExists = true;
                    break;
                }
            }
            
            // 如果选项不存在，则添加该选项
            if (!optionExists) {
                const option = document.createElement('option');
                option.value = value;
                option.text = value;
                option.selected = true;
                select.appendChild(option);
            } else {
                select.value = value;
            }
            
            // 使用layui重新渲染select控件
            if (typeof layui !== 'undefined') {
                layui.use('form', (form) => {
                    form.render('select');
                });
            }
        }
    }

    // 格式化日期时间为input控件格式
    formatDateTimeForInput(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        // 格式化为 YYYY-MM-DDTHH:mm
        return date.getFullYear() + '-' + 
               String(date.getMonth() + 1).padStart(2, '0') + '-' + 
               String(date.getDate()).padStart(2, '0') + 'T' + 
               String(date.getHours()).padStart(2, '0') + ':' + 
               String(date.getMinutes()).padStart(2, '0');
    }

    // 更新工单
    async updateWorkOrder(layerIndex) {
        try {
            // 获取表单数据
            const formData = this.getWorkOrderFormData();
            
            // 验证必填项
            if (!formData.code || !formData.plannedQuantity) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('请填写必填项', {icon: 2});
                    });
                }
                return;
            }

            // 构建更新数据
            const updateData = {
                Id: this.editingWorkOrderId,
                Code: formData.code,
                PlanItemId: formData.planItemId || null,
                RouteId: formData.routeId || null,
                ProductCode: formData.productCode,
                ProductName: formData.productName,
                Spec: formData.spec,
                Unit: formData.unit,
                PlannedQuantity: formData.plannedQuantity,
                ActualQuantity: formData.actualQuantity || 0,
                GoodQuantity: formData.goodQuantity || 0,
                BadQuantity: formData.badQuantity || 0,
                Status: formData.status || null,
                PlannedStartTime: formData.plannedStartTime,
                PlannedEndTime: formData.plannedEndTime,
                ActualStartTime: formData.actualStartTime || null,
                ActualEndTime: formData.actualEndTime || null,
                Remark: formData.remark,
                OperateBy: 'System', // 可以从用户会话中获取
                Processes: (this.selectedProcesses || []).map(process => ({
                    Id: process.id || 0,
                    WorkOrderId: this.editingWorkOrderId,
                    Sequence: process.sequence,
                    ProcessCode: process.processCode,
                    ProcessName: process.processName,
                    PlannedQuantity: process.plannedQuantity || null,
                    ReportedQuantity: process.reportedQuantity || null,
                    GoodQuantity: process.goodQuantity || null,
                    BadQuantity: process.badQuantity || null,
                    Ratio: process.ratio || 1,
                    PlannedStartTime: process.plannedStartTime || null,
                    PlannedEndTime: process.plannedEndTime || null,
                    ActualStartTime: process.actualStartTime || null,
                    ActualEndTime: process.actualEndTime || null,
                    Status: process.status || null,
                    IsDeleted: false,
                    Assigns: process.assigns || []
                }))
            };

            console.log('更新工单数据：', updateData);

            const response = await fetch(`${this.writeApiUrl}/WorkOrder/save`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(updateData)
            });

            const result = await response.json();
            
            if (result.code === 200) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('工单更新成功', {icon: 1});
                        layer.close(layerIndex);
                    });
                }
                this.clearEditingData();
                this.loadWorkOrders(); // 刷新列表
            } else {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('更新失败：' + result.msg, {icon: 2});
                    });
                }
            }
        } catch (error) {
            console.error('更新工单失败:', error);
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    layer.msg('更新失败，请稍后重试', {icon: 2});
                });
            }
        }
    }

    // 清理编辑状态数据
    clearEditingData() {
        this.editingWorkOrderId = null;
        this.selectedProcesses = [];
    }

    // 格式化日期时间
    formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return '';
        const date = new Date(dateTimeStr);
        return date.toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    // 显示加载状态
    showLoading() {
        // 可以添加加载动画
        $('body').append('<div id="loading" class="d-flex justify-content-center align-items-center position-fixed w-100 h-100" style="top:0;left:0;background:rgba(0,0,0,0.1);z-index:9999;"><div class="spinner-border text-primary" role="status"></div></div>');
    }

    // 隐藏加载状态
    hideLoading() {
        $('#loading').remove();
    }

    // 显示错误信息
    showError(message) {
        alert('错误: ' + message);
        // 也可以使用toast或其他提示方式
    }

    // 切换高级搜索显示状态
    toggleAdvancedSearch() {
        if ($('#advancedSearchArea').is(':visible')) {
            this.hideAdvancedSearch();
        } else {
            this.showAdvancedSearch();
        }
    }

    // 显示高级搜索
    showAdvancedSearch() {
        $('#advancedSearchArea').slideDown(300);
        $('#btnAdvancedSearch').text('收起查询').removeClass('btn-outline-info').addClass('btn-outline-warning');
    }

    // 隐藏高级搜索
    hideAdvancedSearch() {
        $('#advancedSearchArea').slideUp(300);
        $('#btnAdvancedSearch').text('高级查询').removeClass('btn-outline-warning').addClass('btn-outline-info');
    }

    // 重置简单搜索
    resetSimpleSearch() {
        $('#searchCode').val('');
    }

    // 重置高级搜索条件
    resetAdvancedSearch() {
        $('#searchProductCode').val('');
        $('#searchProductName').val('');
        $('#searchSpec').val('');
        $('#searchUnit').val('');
        $('#searchActualQuantity').val('');
        $('#searchStatus').val('');
        $('#searchCreateBy').val('');
        
        // 重置时间查询条件
        $('#searchPlannedStartTimeStart').val('');
        $('#searchPlannedStartTimeEnd').val('');
        $('#searchPlannedEndTimeStart').val('');
        $('#searchPlannedEndTimeEnd').val('');
        $('#searchActualStartTimeStart').val('');
        $('#searchActualStartTimeEnd').val('');
        $('#searchActualEndTimeStart').val('');
        $('#searchActualEndTimeEnd').val('');
        $('#searchCreateTimeStart').val('');
        $('#searchCreateTimeEnd').val('');
    }

    // 重置所有搜索条件
    resetAllSearch() {
        this.resetSimpleSearch();
        this.resetAdvancedSearch();
    }

    // 使用Layui Layer显示工单详情弹窗
    showLayerModal(content) {
        // 确保layui已加载
        if (typeof layui !== 'undefined') {
            layui.use('layer', (layer) => {
                layer.open({
                    type: 1,
                    title: '工单详情',
                    area: ['90%', '80%'], // 宽度90%，高度80%
                    maxmin: true, // 允许最大最小化
                    content: content,
                    btn: ['关闭'],
                    btnAlign: 'c',
                    yes: function(index) {
                        layer.close(index);
                    }
                });
            });
        } else {
            // 降级方案：使用原生alert
            this.showError('系统组件未加载完成，请刷新页面重试');
        }
    }

    // 显示新增工单弹窗
    showCreateWorkOrderModal() {
        // 清理编辑状态，确保是新增模式
        this.clearEditingData();
        
        const content = this.renderCreateWorkOrderForm();
        
        if (typeof layui !== 'undefined') {
            layui.use('layer', (layer) => {
                this.createModalIndex = layer.open({
                    type: 1,
                    title: '新增工单',
                    area: ['95%', '85%'],
                    maxmin: true,
                    content: content,
                    btn: ['保存', '取消'],
                    btnAlign: 'c',
                    yes: function(index) {
                        workOrderMgr.saveWorkOrder(index);
                    },
                    btn2: function(index) {
                        layer.close(index);
                    },
                    success: function(layero, index) {
                        // 渲染layui表单
                        layui.use('form', (form) => {
                            form.render();
                            
                            // 加载产品数据到下拉框
                            workOrderMgr.loadProductsToSelect();
                            
                            // 监听产品选择事件
                            workOrderMgr.setupProductSelectListener(form);
                        });
                    }
                });
            });
        } else {
            this.showError('系统组件未加载完成，请刷新页面重试');
        }
    }

    // 渲染新增工单表单
    renderCreateWorkOrderForm() {
        return `
            <div style="padding: 20px; max-height: 600px; overflow-y: auto;">
                <!-- 工单基本信息 -->
                <div class="layui-card">
                    <div class="layui-card-header">工单信息</div>
                    <div class="layui-card-body">
                        <form class="layui-form" id="workOrderForm">
                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md4">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">工单编号<span style="color:red;">*</span></label>
                                        <div class="layui-input-block">
                                            <input type="text" name="code" id="workOrderCode" required lay-verify="required" 
                                                   placeholder="请输入工单编号" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md4">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">产品名称<span style="color:red;">*</span></label>
                                        <div class="layui-input-block">
                                            <select name="productName" id="productName" lay-filter="productSelect" 
                                                    lay-search lay-verify="required" class="layui-select">
                                                <option value="">请选择产品</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md4">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">产品编号</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="productCode" id="productCode" 
                                                   placeholder="产品编号" class="layui-input" readonly>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md4">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">规格</label>
                                        <div class="layui-input-block">
                                            <input type="text" name="spec" id="spec" 
                                                   placeholder="规格" class="layui-input" readonly>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md4">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">单位</label>
                                        <div class="layui-input-block">
                                            <select name="unit" id="unit" class="layui-select">
                                                <option value="">请选择单位</option>
                                                <option value="个">个</option>
                                                <option value="箱">箱</option>
                                                <option value="件">件</option>
                                                <option value="台">台</option>
                                                <option value="套">套</option>
                                                <option value="批">批</option>
                                                <option value="公斤">公斤</option>
                                                <option value="吨">吨</option>
                                                <option value="PCS">PCS</option>
                                                <option value="只">只</option>
                                                <option value="米">米</option>
                                                <option value="条">条</option>
                                                <option value="张">张</option>
                                                <option value="车">车</option>
                                                <option value="天">天</option>
                                                <option value="小时">小时</option>
                                                <option value="分钟">分钟</option>
                                                <option value="周">周</option>
                                                <option value="月">月</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md4">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">计划数量<span style="color:red;">*</span></label>
                                        <div class="layui-input-block">
                                            <input type="number" name="plannedQuantity" id="plannedQuantity" required lay-verify="required|number" 
                                                   placeholder="请输入计划数量" class="layui-input">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-row layui-col-space10">
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">计划开始时间</label>
                                        <div class="layui-input-block">
                                            <input type="datetime-local" name="plannedStartTime" id="plannedStartTime" 
                                                   class="layui-input">
                                        </div>
                                    </div>
                                </div>
                                <div class="layui-col-md6">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">计划结束时间</label>
                                        <div class="layui-input-block">
                                            <input type="datetime-local" name="plannedEndTime" id="plannedEndTime" 
                                                   class="layui-input">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">备注</label>
                                <div class="layui-input-block">
                                    <textarea name="remark" id="remark" placeholder="请输入备注" 
                                              class="layui-textarea" rows="3"></textarea>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 工序信息 -->
                <div class="layui-card" style="margin-top: 15px;">
                    <div class="layui-card-header">
                        工序信息
                        <div style="float: right;">
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-primary" onclick="workOrderMgr.showProcessSelectModal()">
                                <i class="layui-icon layui-icon-add-1"></i> 从工序中添加
                            </button>
                        </div>
                    </div>
                    <div class="layui-card-body">
                        <div id="processTableContainer">
                            <p class="layui-text" style="text-align: center; color: #999; padding: 20px;">
                                暂无工序，请点击"从工序中添加"添加工序
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        `;
    }

    // 显示工序选择弹窗
    showProcessSelectModal() {
        if (typeof layui !== 'undefined') {
            layui.use('layer', (layer) => {
                this.processSelectIndex = layer.open({
                    type: 1,
                    title: '选择工序',
                    area: ['80%', '70%'],
                    content: this.renderProcessSelectForm(),
                    btn: ['确定添加', '取消'],
                    btnAlign: 'c',
                    success: function() {
                        workOrderMgr.loadProcessList();
                    },
                    yes: function(index) {
                        workOrderMgr.addSelectedProcesses(index);
                    }
                });
            });
        }
    }

    // 渲染工序选择表单
    renderProcessSelectForm() {
        return `
            <div style="padding: 15px;">
                <div style="margin-bottom: 15px;">
                    <input type="text" id="processSearch" placeholder="搜索工序名称..." class="layui-input" style="width: 300px; display: inline-block;">
                    <button type="button" class="layui-btn layui-btn-sm" onclick="workOrderMgr.searchProcesses()">搜索</button>
                </div>
                <div id="processSelectContainer">
                    <div style="text-align: center; padding: 20px;">
                        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop"></i>
                        加载中...
                    </div>
                </div>
            </div>
        `;
    }

    // 加载工序列表
    async loadProcessList(searchKeyword = '') {
        try {
            // 调用 /api/Process/all 接口获取所有工序
            const response = await fetch(`${this.readApiUrl}/Process/all`);
            const result = await response.json();

            if (result.code === 200) {
                let processes = result.data || [];
                
                // 如果有搜索关键词，进行客户端过滤
                if (searchKeyword) {
                    processes = processes.filter(process => 
                        process.processName.includes(searchKeyword) ||
                        process.processNumber.includes(searchKeyword)
                    );
                }
                
                this.renderProcessSelectTable(processes);
            } else {
                this.showError('获取工序列表失败：' + result.msg);
            }
        } catch (error) {
            console.error('加载工序列表失败:', error);
            this.showError('加载工序列表失败');
        }
    }

    // 渲染工序选择表格
    renderProcessSelectTable(processes) {
        const container = document.getElementById('processSelectContainer');
        if (!container) return;

        if (processes.length === 0) {
            container.innerHTML = '<div style="text-align: center; padding: 20px; color: #999;">暂无工序数据</div>';
            return;
        }

        let html = `
            <table class="layui-table">
                <thead>
                    <tr>
                        <th width="50"><input type="checkbox" id="selectAllProcess" onclick="workOrderMgr.toggleSelectAll()"></th>
                        <th>工序编号</th>
                        <th>工序名称</th>
                        <th>报工权限</th>
                        <th>报工数配比</th>
                    </tr>
                </thead>
                <tbody>
        `;

        processes.forEach(process => {
            html += `
                <tr>
                    <td><input type="checkbox" name="selectedProcess" value="${process.id}" data-process='${JSON.stringify(process)}'></td>
                    <td>${process.processNumber || ''}</td>
                    <td>${process.processName || ''}</td>
                    <td>${process.reportingPermissions || ''}</td>
                    <td>${process.reportingRatio || 1}</td>
                </tr>
            `;
        });

        html += '</tbody></table>';
        container.innerHTML = html;
    }

    // 搜索工序
    searchProcesses() {
        const keyword = document.getElementById('processSearch').value.trim();
        this.loadProcessList(keyword);
    }

    // 切换全选
    toggleSelectAll() {
        const selectAll = document.getElementById('selectAllProcess');
        const checkboxes = document.querySelectorAll('input[name="selectedProcess"]');
        
        checkboxes.forEach(checkbox => {
            checkbox.checked = selectAll.checked;
        });
    }

    // 添加选中的工序
    addSelectedProcesses(layerIndex) {
        const selectedCheckboxes = document.querySelectorAll('input[name="selectedProcess"]:checked');
        
        if (selectedCheckboxes.length === 0) {
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    layer.msg('请至少选择一个工序', {icon: 2});
                });
            }
            return;
        }

        // 获取已有工序，避免重复添加
        if (!this.selectedProcesses) {
            this.selectedProcesses = [];
        }

        let addedCount = 0;
        selectedCheckboxes.forEach(checkbox => {
            const processData = JSON.parse(checkbox.dataset.process);
            
            // 检查是否已存在（使用工序编号检查）
            const processCode = processData.processNumber || processData.processCode;
            const exists = this.selectedProcesses.some(p => p.processCode === processCode);
            if (!exists) {
                this.selectedProcesses.push({
                    id: 0, // 新增工序ID为0
                    workOrderId: 0, // 工单ID，保存时后端会自动设置
                    sequence: this.selectedProcesses.length + 1,
                    processCode: processData.processNumber || processData.processCode, // 兼容新旧字段名
                    processName: processData.processName,
                    reportingPermissions: processData.reportingPermissions || '无', // 报工权限
                    plannedQuantity: 0, // 默认计划数量
                    reportedQuantity: 0, // 已报工数
                    goodQuantity: 0, // 良品数
                    badQuantity: 0, // 不良品数
                    ratio: processData.reportingRatio || processData.ratio || 1, // 报工配比，兼容新旧字段名
                    plannedStartTime: null, // 计划开始时间
                    plannedEndTime: null, // 计划结束时间
                    actualStartTime: null, // 实际开始时间
                    actualEndTime: null, // 实际结束时间
                    status: '未开始', // 默认状态
                    isDeleted: false, // 删除标记
                    assigns: [] // 工序分派
                });
                addedCount++;
            }
        });

        if (addedCount > 0) {
            this.renderSelectedProcessTable();
            
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    layer.msg(`成功添加 ${addedCount} 个工序`, {icon: 1});
                    layer.close(layerIndex);
                });
            }
        } else {
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    layer.msg('所选工序已存在', {icon: 2});
                });
            }
        }
    }

    // 渲染已选择的工序表格（用于新增/编辑工单）
    renderSelectedProcessTable() {
        const container = document.getElementById('processTableContainer');
        if (!container || !this.selectedProcesses || this.selectedProcesses.length === 0) {
            if (container) {
                container.innerHTML = `
                    <p class="layui-text" style="text-align: center; color: #999; padding: 20px;">
                        暂无工序，请点击"从工序中添加"添加工序
                    </p>
                `;
            }
            return;
        }

        let html = `
            <table class="layui-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>工序编号</th>
                        <th>工序名称</th>
                        <th>报工权限</th>
                        <th>报工数配比</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
        `;

        this.selectedProcesses.forEach((process, index) => {
            html += `
                <tr>
                    <td>${process.sequence}</td>
                    <td>${process.processCode}</td>
                    <td>${process.processName}</td>
                    <td>${process.reportingPermissions || '无'}</td>
                    <td>
                        <input type="number" value="${process.ratio}" 
                               onchange="workOrderMgr.updateProcessField(${index}, 'ratio', parseFloat(this.value) || 1)"
                               class="layui-input" style="width: 80px;" min="0" step="0.1">
                    </td>
                    <td>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" 
                                onclick="workOrderMgr.removeProcess(${index})">删除</button>
                    </td>
                </tr>
            `;
        });

        html += '</tbody></table>';
        container.innerHTML = html;
    }

    // 更新工序字段
    updateProcessField(index, field, value) {
        if (this.selectedProcesses && this.selectedProcesses[index]) {
            this.selectedProcesses[index][field] = value;
        }
    }

    // 兼容旧方法名
    updateProcessQuantity(index, quantity) {
        this.updateProcessField(index, 'plannedQuantity', parseInt(quantity) || 0);
    }

    // 删除工序
    removeProcess(index) {
        if (this.selectedProcesses && this.selectedProcesses[index]) {
            this.selectedProcesses.splice(index, 1);
            // 重新设置序号
            this.selectedProcesses.forEach((process, i) => {
                process.sequence = i + 1;
            });
            this.renderSelectedProcessTable();
        }
    }

    // 保存工单（包含工序数据）
    async saveWorkOrder(layerIndex) {
        // 如果是编辑模式，调用更新方法
        if (this.editingWorkOrderId) {
            return this.updateWorkOrder(layerIndex);
        }
        
        try {
            // 获取表单数据
            const formData = this.getWorkOrderFormData();
            
            // 验证必填项
            if (!formData.code || !formData.plannedQuantity) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('请填写必填项', {icon: 2});
                    });
                }
                return;
            }

            // 构建保存数据
            const saveData = {
                Id: 0,
                Code: formData.code,
                PlanItemId: formData.planItemId || null,
                RouteId: formData.routeId || null,
                ProductCode: formData.productCode,
                ProductName: formData.productName,
                Spec: formData.spec,
                Unit: formData.unit,
                PlannedQuantity: formData.plannedQuantity,
                ActualQuantity: formData.actualQuantity || 0,
                GoodQuantity: formData.goodQuantity || 0,
                BadQuantity: formData.badQuantity || 0,
                Status: formData.status || null,
                PlannedStartTime: formData.plannedStartTime,
                PlannedEndTime: formData.plannedEndTime,
                ActualStartTime: formData.actualStartTime || null,
                ActualEndTime: formData.actualEndTime || null,
                Remark: formData.remark,
                OperateBy: 'System', // 可以从用户会话中获取
                Processes: (this.selectedProcesses || []).map(process => ({
                    Id: 0, // 新增工序ID为0
                    WorkOrderId: 0, // 新增时工单ID为0
                    Sequence: process.sequence,
                    ProcessCode: process.processCode,
                    ProcessName: process.processName,
                    PlannedQuantity: process.plannedQuantity || null,
                    ReportedQuantity: process.reportedQuantity || null,
                    GoodQuantity: process.goodQuantity || null,
                    BadQuantity: process.badQuantity || null,
                    Ratio: process.ratio || 1,
                    PlannedStartTime: process.plannedStartTime || null,
                    PlannedEndTime: process.plannedEndTime || null,
                    ActualStartTime: process.actualStartTime || null,
                    ActualEndTime: process.actualEndTime || null,
                    Status: process.status || null,
                    IsDeleted: false,
                    Assigns: process.assigns || []
                }))
            };

            // 调试：输出保存数据结构
            console.log('保存工单数据：', saveData);
            console.log('工序数据：', saveData.Processes);

            // 发送保存请求
            const response = await fetch(`${this.writeApiUrl}/WorkOrder/save`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(saveData)
            });

            const result = await response.json();

            if (result.code === 200) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('保存成功', {icon: 1}, () => {
                            layer.close(layerIndex);
                            workOrderMgr.currentPage = 1;
                            workOrderMgr.loadWorkOrders(); // 刷新列表
                        });
                    });
                }
                // 重置选中的工序
                this.selectedProcesses = [];
            } else {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('保存失败：' + result.msg, {icon: 2});
                    });
                }
            }
        } catch (error) {
            console.error('保存工单失败:', error);
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    layer.msg('保存失败，请重试', {icon: 2});
                });
            }
        }
    }

    // 获取表单数据
    getWorkOrderFormData() {
        return {
            code: document.getElementById('workOrderCode')?.value || '',
            planItemId: 0, // 默认值，表示无来源计划
            routeId: 0, // 默认值，表示无指定路线
            productCode: document.getElementById('productCode')?.value || '',
            productName: document.getElementById('productName')?.value || '',
            spec: document.getElementById('spec')?.value || '',
            unit: document.getElementById('unit')?.value || '',
            plannedQuantity: parseInt(document.getElementById('plannedQuantity')?.value) || 0,
            actualQuantity: 0,
            goodQuantity: 0,
            badQuantity: 0,
            status: '未开始',
            plannedStartTime: document.getElementById('plannedStartTime')?.value || null,
            plannedEndTime: document.getElementById('plannedEndTime')?.value || null,
            actualStartTime: null,
            actualEndTime: null,
            remark: document.getElementById('remark')?.value || ''
        };
    }

    // 开始工单
    async startWorkOrder(workOrderId) {
        if (!workOrderId) {
            this.showError('工单ID不能为空');
            return;
        }

        try {
            // 弹出确认框
            if (typeof layui !== 'undefined') {
                layui.use('layer', async (layer) => {
                    layer.confirm('确定要开始这个工单吗？', {
                        icon: 3,
                        title: '确认开始'
                    }, async (index) => {
                        layer.close(index);
                        await this.executeStartWorkOrder(workOrderId);
                    });
                });
            } else {
                if (confirm('确定要开始这个工单吗？')) {
                    await this.executeStartWorkOrder(workOrderId);
                }
            }
        } catch (error) {
            console.error('开始工单失败:', error);
            this.showError('开始工单失败');
        }
    }

    // 执行开始工单
    async executeStartWorkOrder(workOrderId) {
        try {
            const response = await fetch(`${this.writeApiUrl}/WorkOrder/${workOrderId}/start?operateBy=admin`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const result = await response.json();

            if (result.code === 200) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('工单开始成功', {icon: 1});
                    });
                } else {
                    alert('工单开始成功');
                }
                // 刷新列表
                this.loadWorkOrders();
                // 清除选择
                this.clearSelection();
            } else {
                this.showError('开始工单失败：' + result.msg);
            }
        } catch (error) {
            console.error('开始工单请求失败:', error);
            this.showError('开始工单失败，请稍后重试');
        }
    }

    // 结束工单
    async finishWorkOrder(workOrderId) {
        if (!workOrderId) {
            this.showError('工单ID不能为空');
            return;
        }

        try {
            // 弹出确认框
            if (typeof layui !== 'undefined') {
                layui.use('layer', async (layer) => {
                    layer.confirm('确定要结束这个工单吗？', {
                        icon: 3,
                        title: '确认结束'
                    }, async (index) => {
                        layer.close(index);
                        await this.executeFinishWorkOrder(workOrderId);
                    });
                });
            } else {
                if (confirm('确定要结束这个工单吗？')) {
                    await this.executeFinishWorkOrder(workOrderId);
                }
            }
        } catch (error) {
            console.error('结束工单失败:', error);
            this.showError('结束工单失败');
        }
    }

    // 执行结束工单
    async executeFinishWorkOrder(workOrderId) {
        try {
            const response = await fetch(`${this.writeApiUrl}/WorkOrder/${workOrderId}/finish?operateBy=admin`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const result = await response.json();

            if (result.code === 200) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('工单结束成功', {icon: 1});
                    });
                } else {
                    alert('工单结束成功');
                }
                // 刷新列表
                this.loadWorkOrders();
                // 清除选择
                this.clearSelection();
            } else {
                this.showError('结束工单失败：' + result.msg);
            }
        } catch (error) {
            console.error('结束工单请求失败:', error);
            this.showError('结束工单失败，请稍后重试');
        }
    }

    // 删除工单
    async deleteWorkOrder(workOrderId) {
        if (!workOrderId) {
            this.showError('工单ID不能为空');
            return;
        }

        try {
            // 弹出确认框
            if (typeof layui !== 'undefined') {
                layui.use('layer', async (layer) => {
                    layer.confirm('确定要删除这个工单吗？删除后将无法恢复！', {
                        icon: 0,
                        title: '确认删除'
                    }, async (index) => {
                        layer.close(index);
                        await this.executeDeleteWorkOrder(workOrderId);
                    });
                });
            } else {
                if (confirm('确定要删除这个工单吗？删除后将无法恢复！')) {
                    await this.executeDeleteWorkOrder(workOrderId);
                }
            }
        } catch (error) {
            console.error('删除工单失败:', error);
            this.showError('删除工单失败');
        }
    }

    // 执行删除工单
    async executeDeleteWorkOrder(workOrderId) {
        try {
            const response = await fetch(`${this.writeApiUrl}/WorkOrder/${workOrderId}?operateBy=admin`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const result = await response.json();

            if (result.code === 200) {
                if (typeof layui !== 'undefined') {
                    layui.use('layer', (layer) => {
                        layer.msg('工单删除成功', {icon: 1});
                    });
                } else {
                    alert('工单删除成功');
                }
                // 刷新列表
                this.loadWorkOrders();
                // 清除选择
                this.clearSelection();
            } else {
                this.showError('删除工单失败：' + result.msg);
            }
        } catch (error) {
            console.error('删除工单请求失败:', error);
            this.showError('删除工单失败，请稍后重试');
        }
    }

    // 工单选择处理
    onWorkOrderSelect(workOrderId, status) {
        this.selectedWorkOrderId = workOrderId;
        this.selectedWorkOrderStatus = status;
        this.updateTopButtonStates(status);
    }

    // 更新顶部按钮状态
    updateTopButtonStates(status) {
        const btnStart = $('#btnStart');
        const btnFinish = $('#btnFinish');
        const btnDelete = $('#btnDelete');

        // 重置所有按钮
        btnStart.prop('disabled', true);
        btnFinish.prop('disabled', true);
        btnDelete.prop('disabled', true);

        if (!status) return;

        // 根据状态启用相应按钮
        switch (status) {
            case '未开始':
                btnStart.prop('disabled', false);
                btnDelete.prop('disabled', false);
                break;
            case '进行中':
                btnFinish.prop('disabled', false);
                break;
            case '已结束':
            case '已完成':
                btnDelete.prop('disabled', false);
                break;
        }
    }

    // 开始选中的工单
    startSelectedWorkOrder() {
        if (!this.selectedWorkOrderId) {
            this.showError('请先选择一个工单');
            return;
        }
        this.startWorkOrder(this.selectedWorkOrderId);
    }

    // 结束选中的工单
    finishSelectedWorkOrder() {
        if (!this.selectedWorkOrderId) {
            this.showError('请先选择一个工单');
            return;
        }
        this.finishWorkOrder(this.selectedWorkOrderId);
    }

    // 删除选中的工单
    deleteSelectedWorkOrder() {
        if (!this.selectedWorkOrderId) {
            this.showError('请先选择一个工单');
            return;
        }
        this.deleteWorkOrder(this.selectedWorkOrderId);
    }

    // 清除选择状态
    clearSelection() {
        this.selectedWorkOrderId = null;
        this.selectedWorkOrderStatus = null;
        // 清除单选框选中状态
        $('input[name="selectedWorkOrder"]').prop('checked', false);
        // 禁用所有顶部按钮
        this.updateTopButtonStates(null);
    }

    // 导出工单数据
    exportWorkOrders() {
        try {
            // 构建导出URL，使用当前搜索条件
            const params = new URLSearchParams();
            
            // 简单搜索条件
            const code = $('#searchCode').val();
            if (code) {
                params.append('workOrderCode', code);
            }

            // 高级搜索条件
            const productCode = $('#searchProductCode').val();
            const productName = $('#searchProductName').val();
            const spec = $('#searchSpec').val();
            const unit = $('#searchUnit').val();
            const actualQuantity = $('#searchActualQuantity').val();
            const status = $('#searchStatus').val();
            const createBy = $('#searchCreateBy').val();

            if (productCode) params.append('productCode', productCode);
            if (productName) params.append('productName', productName);
            if (spec) params.append('spec', spec);
            if (unit) params.append('unit', unit);
            if (actualQuantity) params.append('actualQuantity', actualQuantity);
            if (status) params.append('status', status);
            if (createBy) params.append('createBy', createBy);

            // 时间范围搜索条件
            const plannedStartTimeStart = $('#searchPlannedStartTimeStart').val();
            const plannedStartTimeEnd = $('#searchPlannedStartTimeEnd').val();
            const plannedEndTimeStart = $('#searchPlannedEndTimeStart').val();
            const plannedEndTimeEnd = $('#searchPlannedEndTimeEnd').val();
            const actualStartTimeStart = $('#searchActualStartTimeStart').val();
            const actualStartTimeEnd = $('#searchActualStartTimeEnd').val();
            const actualEndTimeStart = $('#searchActualEndTimeStart').val();
            const actualEndTimeEnd = $('#searchActualEndTimeEnd').val();
            const createTimeStart = $('#searchCreateTimeStart').val();
            const createTimeEnd = $('#searchCreateTimeEnd').val();

            if (plannedStartTimeStart) params.append('plannedStartTimeStart', plannedStartTimeStart);
            if (plannedStartTimeEnd) params.append('plannedStartTimeEnd', plannedStartTimeEnd);
            if (plannedEndTimeStart) params.append('plannedEndTimeStart', plannedEndTimeStart);
            if (plannedEndTimeEnd) params.append('plannedEndTimeEnd', plannedEndTimeEnd);
            if (actualStartTimeStart) params.append('actualStartTimeStart', actualStartTimeStart);
            if (actualStartTimeEnd) params.append('actualStartTimeEnd', actualStartTimeEnd);
            if (actualEndTimeStart) params.append('actualEndTimeStart', actualEndTimeStart);
            if (actualEndTimeEnd) params.append('actualEndTimeEnd', actualEndTimeEnd);
            if (createTimeStart) params.append('createTimeStart', createTimeStart);
            if (createTimeEnd) params.append('createTimeEnd', createTimeEnd);

            // 构建完整的导出URL
            const exportUrl = `${this.readApiUrl}/WorkOrder/export?${params.toString()}`;

            // 创建隐藏的下载链接并点击
            const downloadLink = document.createElement('a');
            downloadLink.href = exportUrl;
            downloadLink.download = `工单数据导出_${new Date().getTime()}.csv`;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);

            // 显示导出提示
            if (typeof layui !== 'undefined') {
                layui.use('layer', (layer) => {
                    layer.msg('导出任务已开始，请稍等...', {icon: 1});
                });
            } else {
                alert('导出任务已开始，请稍等...');
            }

        } catch (error) {
            console.error('导出工单失败:', error);
            this.showError('导出工单失败');
        }
    }

    // 加载产品数据到下拉框
    async loadProductsToSelect() {
        try {
            // 调用查询所有计划明细的接口获取产品数据
            const apiUrl = window.ApiConfig ? window.ApiConfig.readApiUrl : 'http://localhost:5089/api';
            console.log('正在调用API:', `${apiUrl}/Plan/items/all`);
            
            const response = await fetch(`${apiUrl}/Plan/items/all?index=1&size=1000`, {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            });

            console.log('API响应状态:', response.status, response.statusText);

            if (response.ok) {
                const result = await response.json();
                console.log('API响应数据:', result);
                
                if (result.code === 200 && result.pageData) {
                    // 汇总产品数据（根据产品编号合并，数量相加）
                    const productMap = new Map();
                    
                    result.pageData.forEach(item => {
                        const key = item.productCode;
                        if (productMap.has(key)) {
                            // 累加数量
                            const existing = productMap.get(key);
                            existing.quantity = (existing.quantity || 0) + (item.quantity || 0);
                        } else {
                            // 新增产品
                            productMap.set(key, {
                                productCode: item.productCode,
                                productName: item.productName,
                                spec: item.spec || '',
                                unit: item.unit || '',
                                quantity: item.quantity || 1
                            });
                        }
                    });

                    // 转换为数组
                    const uniqueProducts = Array.from(productMap.values());
                    console.log('汇总后的产品数据:', uniqueProducts);

                    // 填充产品下拉框
                    const productSelect = document.getElementById('productName');
                    if (productSelect) {
                        // 清空现有选项（保留第一个空选项）
                        productSelect.innerHTML = '<option value="">请选择产品</option>';
                        
                        // 添加产品选项
                        uniqueProducts.forEach(product => {
                            const option = document.createElement('option');
                            option.value = product.productName;
                            option.textContent = product.productName;
                            option.dataset.productCode = product.productCode;
                            option.dataset.spec = product.spec;
                            option.dataset.unit = product.unit;  // 存储单位信息
                            option.dataset.quantity = product.quantity;  // 存储计划数量
                            productSelect.appendChild(option);
                        });

                        // 重新渲染layui select
                        layui.use('form', (form) => {
                            form.render('select');
                        });
                    }
                }
            } else {
                console.error('加载产品数据失败，状态码:', response.status);
                const errorText = await response.text();
                console.error('错误响应:', errorText);
                
                // 显示用户友好的错误信息
                if (response.status === 404) {
                    console.warn('API接口未找到，请确认Read API项目是否正在运行在端口5089');
                    layui.use('layer', function(layer) {
                        layer.msg('无法连接到数据服务，请联系管理员', {icon: 2});
                    });
                } else {
                    layui.use('layer', function(layer) {
                        layer.msg('加载产品数据失败，请重试', {icon: 2});
                    });
                }
            }
        } catch (error) {
            console.error('加载产品数据出错:', error);
            layui.use('layer', function(layer) {
                layer.msg('网络连接异常，请检查网络或联系管理员', {icon: 2});
            });
        }
    }

    // 设置产品选择监听器
    setupProductSelectListener(form) {
        // 监听产品选择事件
        form.on('select(productSelect)', (data) => {
            const selectedOption = data.elem.selectedOptions[0];
            if (selectedOption && selectedOption.dataset.productCode) {
                // 自动赋值产品编号、规格、单位和计划数量
                const productCodeInput = document.getElementById('productCode');
                const specInput = document.getElementById('spec');
                const unitSelect = document.getElementById('unit');
                const plannedQuantityInput = document.getElementById('plannedQuantity');
                
                if (productCodeInput) {
                    productCodeInput.value = selectedOption.dataset.productCode;
                }
                
                if (specInput) {
                    specInput.value = selectedOption.dataset.spec || '';
                }
                
                // 设置单位下拉框
                if (unitSelect && selectedOption.dataset.unit) {
                    unitSelect.value = selectedOption.dataset.unit;
                    // 重新渲染layui select
                    layui.use('form', (form) => {
                        form.render('select');
                    });
                }
                
                if (plannedQuantityInput && selectedOption.dataset.quantity) {
                    plannedQuantityInput.value = selectedOption.dataset.quantity;
                }
                
                console.log('自动填充数据:', {
                    productCode: selectedOption.dataset.productCode,
                    spec: selectedOption.dataset.spec,
                    unit: selectedOption.dataset.unit,
                    quantity: selectedOption.dataset.quantity
                });
            } else {
                // 清空相关字段
                const productCodeInput = document.getElementById('productCode');
                const specInput = document.getElementById('spec');
                const unitSelect = document.getElementById('unit');
                const plannedQuantityInput = document.getElementById('plannedQuantity');
                
                if (productCodeInput) {
                    productCodeInput.value = '';
                }
                
                if (specInput) {
                    specInput.value = '';
                }
                
                if (unitSelect) {
                    unitSelect.value = '';
                    // 重新渲染layui select
                    layui.use('form', (form) => {
                        form.render('select');
                    });
                }
                
                if (plannedQuantityInput) {
                    plannedQuantityInput.value = '';
                }
            }
        });
    }
}

// 页面加载完成后初始化
$(document).ready(function() {
    window.workOrderMgr = new WorkOrderManagement();
});
